// pages/order/order.js
const { menuManager } = require('../../data/menuManager.js');
const apiService = require('../../utils/apiService.js');

// 根据API返回的status字段设置状态描述
const getStatusDesc = (status) => {
  switch (status) {
    case 'active':
      return '进行中';
    case 'closed':
      return '已关闭';
    case 'expired':
      return '已过期';
    default:
      return '进行中';
  }
};

Page({
  data: {
    // 房间信息
    roomInfo: {
      title: '',
      type: '', // temporary | permanent
      typeIcon: '',
      typeText: '',
      statusDesc: '',
      canManage: false
    },
    
    // 分类
    activeCategory: 0, // 使用分类索引
    activeKey: 0, // van-sidebar 的选中状态
    categories: [], // 分类数据从API获取
    
    // 菜品数据
    menuItems: [],
    filteredMenuItems: [],
    
    // 我的选单
    myOrderItems: [],
    myOrderCount: 0,
    
    // 房间统计信息
    participantCount: 1,
    currentRound: 1,
    totalOrders: 0,
    
    // 餐车弹层
    showCartPopup: false,
    
    // 页面状态
    hasRoom: false
  },

  onLoad(options) {
    // 获取房间ID等参数（优先从全局数据获取）
    const app = getApp();
    let roomId, roomTitle, roomType, participantCount, currentRound;

    // console.log('order', app.globalData.currentRoom);
    
    if (app.globalData.currentRoom) {
      // 从全局数据获取房间信息
      const currentRoom = app.globalData.currentRoom;
      roomId = currentRoom.roomId;
      roomTitle = currentRoom.roomTitle;
      roomType = currentRoom.roomType;
      participantCount = currentRoom.participantCount;
      currentRound = currentRoom.currentRound;
    } else {
      // 从URL参数获取房间信息
      roomId = options.roomId || options.room_id;
      roomTitle = options.roomTitle ? decodeURIComponent(options.roomTitle) : '';
      roomType = options.roomType || '';
      participantCount = parseInt(options.participantCount) || 1;
      currentRound = parseInt(options.currentRound) || 1;
    }
    
    // 检查是否有房间ID
    if (!roomId) {
      this.setData({ hasRoom: false });
      this.checkUserRooms();
      return;
    }
    
    // 更新房间信息
    this.setData({
      'roomInfo.title': roomTitle,
      'roomInfo.roomId': roomId,
      'roomInfo.type': roomType,
      'roomInfo.typeIcon': roomType === 'temporary' ? '⏰' : '🏠',
      'roomInfo.typeText': roomType === 'temporary' ? '临时' : '永久',
      'roomInfo.statusDesc': getStatusDesc('active'), // 默认状态为进行中
      participantCount,
      currentRound,
      hasRoom: true,
      activeKey: 0 // 初始化选中状态
    });
    
    // 异步加载房间信息和菜单数据
    this.loadRoomInfo(roomId).then(() => {
      // 房间信息加载完成后，再加载菜单数据
      this.loadMenuData();
    }).catch(error => {
      // 即使房间信息加载失败，也尝试加载菜单数据
      this.loadMenuData();
    });
  },

  onShow() {
    // 每次显示页面时都检查房间状态，确保房间信息是最新的
    this.checkRoomStatus();
    this.updateMyOrderCount();
  },

  // 检查房间状态
  checkRoomStatus() {
    const app = getApp();
    const currentRoom = app.globalData.currentRoom;
    
    if (currentRoom && currentRoom.roomId) {
      // 检查房间信息是否有变化
      const currentRoomId = this.data.roomInfo.roomId;
      const newRoomId = currentRoom.roomId;
      
      // 如果房间ID不同，说明切换了房间，需要更新信息
      if (currentRoomId !== newRoomId) {
        // 有房间数据，重新设置房间信息
        this.setData({
          'roomInfo.title': currentRoom.roomTitle || '',
          'roomInfo.roomId': currentRoom.roomId,
          'roomInfo.type': currentRoom.roomType || '',
          'roomInfo.typeIcon': currentRoom.roomType === 'temporary' ? '⏰' : '🏠',
          'roomInfo.typeText': currentRoom.roomType === 'temporary' ? '临时' : '永久',
          'roomInfo.statusDesc': getStatusDesc('active'), // 默认状态为进行中
          participantCount: currentRoom.participantCount || 1,
          currentRound: currentRoom.currentRound || 1,
          hasRoom: true,
          activeKey: 0
        });
        
        // 重新加载房间信息和菜单数据
        this.loadRoomInfo(currentRoom.roomId).then(() => {
          this.loadMenuData();
        }).catch(error => {
          this.loadMenuData();
        });
      }
      // 如果房间ID相同，不需要更新，保持当前状态
    } else {
      // 没有房间数据，显示提示
      this.showNoRoomSelected();
    }
  },

  // 检查用户房间（简化版）
  checkUserRooms() {
    // 从全局数据获取当前房间信息
    const app = getApp();
    const currentRoom = app.globalData.currentRoom;
    
    if (!currentRoom || !currentRoom.roomId) {
      // 没有当前房间，显示创建房间提示
      this.showNoRoomSelected();
    } else {
      // 有当前房间，直接进入
      this.autoEnterRoom(currentRoom);
    }
  },

  // 自动进入房间
  async autoEnterRoom(room) {
    const app = getApp();
    
    // 如果传入的是全局房间数据格式，直接使用
    let roomData;
    if (room.roomId) {
      roomData = room;
    } else {
      // 如果传入的是API房间数据格式，转换为全局格式
      roomData = {
        roomId: room.room_id,
        roomTitle: room.title,
        roomType: room.type,
        roomDesc: room.description || '',
        participantCount: room.members_count || 1,
        currentRound: room.current_round || 1
      };
    }
    
    // 设置全局房间数据
    app.globalData.currentRoom = roomData;
    
    // 先设置基础页面数据
    this.setData({
      'roomInfo.title': roomData.roomTitle,
      'roomInfo.roomId': roomData.roomId,
      'roomInfo.type': roomData.roomType,
      'roomInfo.typeIcon': roomData.roomType === 'temporary' ? '⏰' : '🏠',
      'roomInfo.typeText': roomData.roomType === 'temporary' ? '临时' : '永久',
      'roomInfo.statusDesc': getStatusDesc('active'), // 默认状态为进行中
      participantCount: roomData.participantCount,
      currentRound: roomData.currentRound,
      hasRoom: true,
      activeKey: 0
    });
    
    // 通过API获取最新的房间信息和菜单数据
    try {
      await this.loadRoomInfo(roomData.roomId);
      await this.loadMenuData();
    } catch (error) {
      // console.error('加载房间数据失败:', error);
      // 即使API失败，也尝试加载菜单数据
      await this.loadMenuData();
    }
  },


  // 显示未选择房间的提示
  showNoRoomSelected() {
    wx.showModal({
      title: '🏠 还没有房间',
      content: '请先创建一个房间，然后开始点菜吧～',
      showCancel: true,
      cancelText: '稍后再说',
      confirmText: '去创建房间',
      confirmColor: '#07C160',
      success: (res) => {
        if (res.confirm) {
          // 跳转到首页
          wx.switchTab({
            url: '/pages/index/index'
          });
        } else {
          // 用户取消，也跳转到首页
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      }
    });
  },

  // 跳转到首页
  goToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 加载房间信息
  async loadRoomInfo(roomId) {
    if (roomId) {
      try {
        // 调用API获取房间信息
        const roomData = await apiService.getRoomInfo(roomId);
        

        const roomInfo = {
          title: roomData.title,
          type: roomData.type,
          typeIcon: roomData.type === 'temporary' ? '⏰' : '🏠',
          typeText: roomData.type === 'temporary' ? '临时' : '永久',
          statusDesc: getStatusDesc(roomData.status),
          canManage: true,
          roomId: roomData.room_id,
          participantCount: roomData.members_count || roomData.members?.length || 1,
          currentRound: roomData.current_round || 1,
          totalOrders: roomData.total_orders || 0
        };
        
        // 只更新可能变化的数据，不覆盖已经正确设置的房间信息
        this.setData({
          'roomInfo.statusDesc': roomInfo.statusDesc,
          'roomInfo.participantCount': roomInfo.participantCount,
          'roomInfo.currentRound': roomInfo.currentRound,
          'roomInfo.totalOrders': roomInfo.totalOrders,
          participantCount: roomInfo.participantCount,
          currentRound: roomInfo.currentRound,
          totalOrders: roomInfo.totalOrders
        });
        return Promise.resolve();
        
      } catch (error) {
        
        // 如果API失败，使用当前已有的房间信息
        
        // 尝试从全局数据获取更多信息
        const app = getApp();
        if (app.globalData.currentRoom) {
          const currentRoom = app.globalData.currentRoom;
          const roomInfo = {
            title: currentRoom.roomTitle,
            type: currentRoom.roomType,
            typeIcon: currentRoom.roomType === 'temporary' ? '⏰' : '🏠',
            typeText: currentRoom.roomType === 'temporary' ? '临时' : '永久',
            statusDesc: getStatusDesc(currentRoom.status || 'active'), // 使用房间状态，默认为进行中
            canManage: true,
            roomId: currentRoom.roomId,
            participantCount: currentRoom.participantCount,
            currentRound: currentRoom.currentRound
          };
          
          this.setData({
            roomInfo,
            participantCount: currentRoom.participantCount,
            currentRound: currentRoom.currentRound
          });
        }
        
        // 显示提示信息
        wx.showToast({
          title: '房间信息加载中...',
          icon: 'loading',
          duration: 1000
        });
        
        return Promise.reject(error);
      }
    }
    
    // 默认房间信息
    const defaultRoomInfo = {
      title: '',
      type: '',
      typeIcon: '',
      typeText: '',
      statusDesc: '',
      canManage: false
    };
    
    this.setData({
      roomInfo: defaultRoomInfo
    });
    
    return Promise.resolve();
  },

  // 加载房间统计信息
  loadRoomStats(roomId) {
    // 从本地存储加载订单数据
    const orders = wx.getStorageSync('orders') || [];
    const roomOrders = orders.filter(order => order.roomId === roomId);
    
    // 计算统计信息
    const participantCount = Math.max(1, roomOrders.length > 0 ? roomOrders.length : 1);
    const currentRound = 1; // 暂时固定为1
    const totalOrders = roomOrders.length;
    
    this.setData({
      participantCount: participantCount,
      currentRound: currentRound,
      totalOrders: totalOrders
    });
  },

  // 加载菜单数据
  async loadMenuData() {
    // 迁移现有房间数据（首次运行）
    menuManager.migrateExistingRooms();
    
    // 获取当前房间ID
    const roomId = this.data.roomInfo.roomId;
    
    
    if (roomId) {
      try {
        // 调用API获取房间菜单
        const menuData = await apiService.getRoomMenu(roomId);

        // console.log('menuData', menuData);
        // console.log('menuData.categories', menuData.categories);
        // console.log('menuData.dishes', menuData.dishes);
        
        // 更新分类数据
        if (menuData.categories && menuData.categories.length > 0) {
          this.setData({
            categories: menuData.categories
          });
        }
        
        
        // 格式化菜品数据，根据API文档处理字段
        const formattedDishes = (menuData.dishes || []).map(dish => ({
          id: dish.id,
          name: dish.name,
          description: this.formatDescription(dish.description),
          image: dish.image,
          category: dish.category,
          tags: dish.tags || [],
          flavors: dish.flavors || [],
          cookingTime: dish.cookingTime || dish.cooking_time || 0,
          isFeatured: dish.isFeatured || dish.is_featured || false,
          isAvailable: dish.isAvailable !== undefined ? dish.isAvailable : (dish.is_available !== undefined ? dish.is_available : true),
          sortOrder: dish.sortOrder || dish.sort_order || 0,
          viewCount: dish.viewCount || dish.view_count || 0,
          orderCount: dish.orderCount || dish.order_count || 0
        }));
        
        this.setData({
          menuItems: formattedDishes,
          filteredMenuItems: formattedDishes
        });
        
      } catch (error) {
        
        // 如果API失败，使用本地菜单数据
        const roomMenuItems = menuManager.loadRoomMenu(roomId);
        
        // 格式化本地菜品数据
        const formattedRoomMenuItems = roomMenuItems.map(dish => ({
          id: dish.id,
          name: dish.name,
          description: this.formatDescription(dish.description),
          image: dish.image,
          category: dish.category,
          tags: dish.tags || [],
          flavors: dish.flavors || [],
          cookingTime: dish.cookingTime || dish.cooking_time || 0,
          isFeatured: dish.isFeatured || dish.is_featured || false,
          isAvailable: dish.isAvailable !== undefined ? dish.isAvailable : (dish.is_available !== undefined ? dish.is_available : true),
          sortOrder: dish.sortOrder || dish.sort_order || 0,
          viewCount: dish.viewCount || dish.view_count || 0,
          orderCount: dish.orderCount || dish.order_count || 0
        }));
        
        this.setData({
          menuItems: formattedRoomMenuItems,
          filteredMenuItems: formattedRoomMenuItems
        });
      }
    } else {
      // 使用默认菜单
      const defaultMenuItems = menuManager.loadDefaultMenu();
      
      // 格式化默认菜单数据
      const formattedDefaultMenuItems = defaultMenuItems.map(dish => ({
        id: dish.id,
        name: dish.name,
        description: this.formatDescription(dish.description),
        image: dish.image,
        category: dish.category,
        tags: dish.tags || [],
        flavors: dish.flavors || [],
        cookingTime: dish.cookingTime || dish.cooking_time || 0,
        isFeatured: dish.isFeatured || dish.is_featured || false,
        isAvailable: dish.isAvailable !== undefined ? dish.isAvailable : (dish.is_available !== undefined ? dish.is_available : true),
        sortOrder: dish.sortOrder || dish.sort_order || 0,
        viewCount: dish.viewCount || dish.view_count || 0,
        orderCount: dish.orderCount || dish.order_count || 0
      }));
      
      this.setData({
        menuItems: formattedDefaultMenuItems,
        filteredMenuItems: formattedDefaultMenuItems
      });
    }
    
    // 初始化筛选
    this.filterMenuItems();
  },


  // 分类切换
  onCategoryChange(e) {
    // Vant侧边栏事件参数格式：e.detail 是选中的索引
    const selectedIndex = e.detail;
    
    // 方法1：同时更新两个变量
    this.setData({
      activeCategory: selectedIndex,  // 用于筛选逻辑
      activeKey: selectedIndex       // 用于 van-sidebar 选中状态
    });

    // 方法2：分别更新（如果你想要更明确）
    // this.setData({
    //   activeCategory: selectedIndex
    // });
    // this.setData({
    //   activeKey: selectedIndex
    // });

    // 方法3：使用解构赋值（如果你想要更简洁）
    // this.setData({
    //   ...this.data,
    //   activeCategory: selectedIndex,
    //   activeKey: selectedIndex
    // });

    this.filterMenuItems();
  },

  // 筛选菜品
  filterMenuItems() {
    const { menuItems, activeCategory, categories } = this.data;
    let filtered = [...menuItems];

    // 按分类筛选（只有在有分类数据时才进行筛选）
    if (activeCategory !== undefined && activeCategory !== 0 && categories && categories.length > 0) {
      // 根据索引获取分类信息
      const selectedCategory = categories[activeCategory];
      if (selectedCategory) {
        const categorySlug = selectedCategory.slug || 'all';
        
        filtered = filtered.filter(item => {
          // 根据API文档，菜品使用category字段，可能是分类名称或slug
          const match = item.category === categorySlug || 
                       item.category === selectedCategory.name ||
                       item.category === selectedCategory.id;
          return match;
        });
      }
    }

    this.setData({
      filteredMenuItems: filtered
    });
  },

  // 菜品点击
  onDishClick(e) {
    const dish = e.currentTarget.dataset.dish;
  },

  // 添加菜品
  onAddDish(e) {
    const dish = e.currentTarget.dataset.dish;
    this.addDishToOrder(dish);
    
    // 添加点击反馈动画
    this.addClickFeedback(e.currentTarget);
  },

  // 点击反馈动画
  addClickFeedback(target) {
    // 小程序中通过添加临时类名实现动画
    if (target && target.classList) {
      target.classList.add('clicked');
      setTimeout(() => {
        target.classList.remove('clicked');
      }, 300);
    } else if (target && target.style) {
      // 备用方案：通过修改样式实现
      try {
        const originalTransform = target.style.transform || '';
        target.style.transform = 'scale(1.2)';
        target.style.transition = 'transform 0.3s ease-out';
        
        setTimeout(() => {
          target.style.transform = originalTransform;
          setTimeout(() => {
            target.style.transition = '';
          }, 300);
        }, 150);
      } catch (error) {
        console.warn('点击动画失败:', error);
      }
    } else {
      // 静默处理，不显示警告
      // console.warn('无法添加点击动画，target无效');
    }
  },

  // 减少菜品数量
  onDecreaseDish(e) {
    const dish = e.currentTarget.dataset.dish;
    this.decreaseDishFromOrder(dish);
  },

  // 移除菜品（在菜品列表中点击已选中的菜品）
  onRemoveDish(e) {
    const dishId = e.currentTarget.dataset.dishId;
    this.removeDishFromOrder(dishId);
  },


  // 我的选单相关
  addDishToOrder(dish) {
    const { myOrderItems } = this.data;
    
    
    // 检查是否已存在相同菜品
    const existingIndex = myOrderItems.findIndex(item => item.id === dish.id);

    if (existingIndex >= 0) {
      // 如果已存在，则移除（取消选择）
      myOrderItems.splice(existingIndex, 1);
    } else {
      // 添加新菜品（选择一份）
      myOrderItems.push({
        id: dish.id,
        name: dish.name,
        image: dish.image,
        quantity: 1
      });
    }

    // 更新菜品选择状态
    this.updateDishSelectionStatus();

    this.setData({
      myOrderItems
    });
    this.updateMyOrderCount();
    this.updateMenuItemsCount();
  },

  // 更新菜品选择状态
  updateDishSelectionStatus() {
    const { myOrderItems, filteredMenuItems } = this.data;
    
    // 安全检查：确保filteredMenuItems存在且是数组
    if (!filteredMenuItems || !Array.isArray(filteredMenuItems)) {
      console.warn('filteredMenuItems is not available for selection status update');
      return;
    }
    
    // 为每个菜品添加选择状态和数量
    const updatedMenuItems = filteredMenuItems.map(dish => {
      const orderItem = myOrderItems.find(item => item.id === dish.id);
      const updatedDish = {
        ...dish,
        selected: !!orderItem,
        quantity: orderItem ? orderItem.quantity : 0
      };
      
      
      return updatedDish;
    });


    // 更新菜品选择状态
    this.setData({
      filteredMenuItems: updatedMenuItems
    });
  },

  // 减少菜品数量
  decreaseDishFromOrder(dish) {
    const { myOrderItems } = this.data;
    const existingIndex = myOrderItems.findIndex(item => item.id === dish.id);

    if (existingIndex >= 0) {
      if (myOrderItems[existingIndex].quantity > 1) {
        // 如果数量大于1，则减1
        myOrderItems[existingIndex].quantity -= 1;
      } else {
        // 如果数量为1，则移除该菜品
        myOrderItems.splice(existingIndex, 1);
      }
      
      this.setData({
        myOrderItems: myOrderItems
      });
      this.updateMyOrderCount();
      this.updateMenuItemsCount();
    }
  },

  removeDishFromOrder(dishId) {
    const { myOrderItems } = this.data;
    const filtered = myOrderItems.filter(item => item.id !== dishId);
    
    this.setData({
      myOrderItems: filtered
    });
    this.updateMyOrderCount();
    this.updateMenuItemsCount();
  },

  updateDishQuantity(dishId, change) {
    const { myOrderItems } = this.data;
    const itemIndex = myOrderItems.findIndex(item => item.id === dishId);
    
    if (itemIndex >= 0) {
      myOrderItems[itemIndex].quantity += change;
      if (myOrderItems[itemIndex].quantity <= 0) {
        myOrderItems.splice(itemIndex, 1);
      }
      
      this.setData({
        myOrderItems
      });
      this.updateMyOrderCount();
      this.updateMenuItemsCount();
    }
  },

  updateMyOrderCount() {
    const { myOrderItems } = this.data;
    const count = myOrderItems.reduce((sum, item) => sum + item.quantity, 0);
    
    this.setData({
      myOrderCount: count
    });
  },

  // 格式化菜品描述，支持换行
  formatDescription(description) {
    if (!description) return '';
    
    // 将换行符转换为HTML换行标签
    return description
      .replace(/\n/g, '<br/>')
      .replace(/\r\n/g, '<br/>')
      .replace(/\r/g, '<br/>');
  },

  updateMenuItemsCount() {
    const { menuItems, myOrderItems } = this.data;
    
    const updatedMenuItems = menuItems.map(dish => {
      const totalQuantity = myOrderItems
        .filter(item => item.id === dish.id)
        .reduce((sum, item) => sum + item.quantity, 0);
      
      // 处理菜品描述换行
      const processedDish = { ...dish, count: totalQuantity };
      if (processedDish.description) {
        processedDish.description = this.formatDescription(processedDish.description);
      }
      
      return processedDish;
    });

    // 保留现有的选择状态（myOrderItems已在上面声明）
    
    // 为每个菜品添加选择状态
    const updatedMenuItemsWithSelection = updatedMenuItems.map(dish => {
      const orderItem = myOrderItems.find(item => item.id === dish.id);
      return {
        ...dish,
        selected: !!orderItem,
        quantity: orderItem ? orderItem.quantity : 0
      };
    });

    this.setData({
      menuItems: updatedMenuItemsWithSelection,
      filteredMenuItems: updatedMenuItemsWithSelection.filter(item => {
        const { activeCategory, categories } = this.data;
        
        // 分类筛选（只有在有分类数据时才进行筛选）
        if (activeCategory > 0 && categories && categories.length > 0) {
          const selectedCategory = categories[activeCategory];
          if (selectedCategory) {
            const categorySlug = selectedCategory.slug || 'all';
            
            // 根据API文档，菜品使用category字段，可能是分类名称或slug
            const match = item.category === categorySlug || 
                         item.category === selectedCategory.name ||
                         item.category === selectedCategory.id;
            if (!match) return false;
          }
        }
        
        return true;
      })
    });
  },

  // 餐车弹层
  showCartPopup() {
    this.setData({
      showCartPopup: true
    });
  },

  // 空餐车提示
  showEmptyCartTip() {
    wx.showToast({
      title: '餐车是空的，去点菜吧',
      icon: 'none',
      duration: 2000
    });
  },

  onCloseCartPopup() {
    this.setData({
      showCartPopup: false
    });
  },

  onCartDecreaseQuantity(e) {
    const item = e.currentTarget.dataset.item;
    if (item.quantity > 1) {
      this.updateCartItemQuantity(item.id, -1);
    } else {
      this.removeCartItem(item.id);
    }
  },

  onCartIncreaseQuantity(e) {
    const item = e.currentTarget.dataset.item;
    this.updateCartItemQuantity(item.id, 1);
  },

  onCartRemoveItem(e) {
    const item = e.currentTarget.dataset.item;
    this.removeCartItem(item.id);
  },

  onClearCart() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空餐车吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            myOrderItems: []
          });
          this.updateMyOrderCount();
          this.updateMenuItemsCount();
        }
      }
    });
  },

  updateCartItemQuantity(itemId, change) {
    const { myOrderItems } = this.data;
    const itemIndex = myOrderItems.findIndex(item => item.id === itemId);
    
    if (itemIndex >= 0) {
      myOrderItems[itemIndex].quantity += change;
      if (myOrderItems[itemIndex].quantity <= 0) {
        myOrderItems.splice(itemIndex, 1);
      }
      
      this.setData({
        myOrderItems
      });
      this.updateMyOrderCount();
      this.updateMenuItemsCount();
    }
  },

  removeCartItem(itemId) {
    const { myOrderItems } = this.data;
    const filtered = myOrderItems.filter(item => item.id !== itemId);
    
    this.setData({
      myOrderItems: filtered
    });
    this.updateMyOrderCount();
    this.updateMenuItemsCount();
  },

  clearCart() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空餐车吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            myOrderItems: []
          });
          this.updateMyOrderCount();
          this.updateMenuItemsCount();
          this.setData({
            showCartPopup: false
          });
        }
      }
    });
  },

  onMyOrderQuantityChange(e) {
    const value = e.detail;
    const item = e.currentTarget.dataset.item;
    
    if (value === 0) {
      this.removeDishFromOrder(item.id);
    } else {
      this.updateDishQuantity(item.id, value);
    }
  },

  onRemoveOrderItem(e) {
    const item = e.currentTarget.dataset.item;
    this.removeDishFromOrder(item.id);
  },

  clearMyOrder() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有选单吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            myOrderItems: []
          });
          this.updateMyOrderCount();
          this.updateMenuItemsCount();
        }
      }
    });
  },

  // 其他功能
  startNewRound() {
    wx.showToast({
      title: '开启新一轮功能开发中',
      icon: 'none'
    });
  },

  goToSummary() {
    if (this.data.myOrderItems.length === 0) {
      // 餐车为空时，提示用户去点菜
      wx.showToast({
        title: '餐车是空的，去点菜吧',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.showModal({
      title: '确认下单',
      content: `共选择${this.data.myOrderCount}份菜品，确认提交订单吗？`,
      confirmText: '确认下单',
      cancelText: '继续选择',
      success: (res) => {
        if (res.confirm) {
          this.submitOrder();
        }
      }
    });
  },

  // 跳转到菜单管理
  goToMenuManagement() {
    wx.showModal({
      title: '功能开发中',
      content: '菜单管理功能正在开发中，敬请期待！\n\n您可以：\n• 使用默认菜单\n• 创建自定义菜单\n• 管理菜品信息',
      showCancel: true,
      cancelText: '知道了',
      confirmText: '查看详情',
      confirmColor: 'var(--color-primary)',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '功能即将上线',
            icon: 'none',
            duration: 2000
          });
        }
      }
    });
  },

  // 提交订单
  async submitOrder() {
    wx.showLoading({
      title: '提交中...'
    });

    try {
      // 使用统一的登录守卫检查
      const authGuard = require('../../utils/authGuard.js');
      
      if (!authGuard.beforeApiCall()) {
        wx.hideLoading();
        return;
      }

      // 准备订单数据
      const orderData = {
        roomId: this.data.roomInfo.roomId || 'default',
        dishes: this.data.myOrderItems.map(item => {
          const dish = {
            dishId: item.id,
            quantity: item.quantity
          };
          
          // 只有当flavor和note有实际内容时才添加，避免空字符串
          if (item.flavor && item.flavor.trim()) {
            dish.flavor = item.flavor.trim();
          }
          if (item.note && item.note.trim()) {
            dish.note = item.note.trim();
          }
          
          return dish;
        })
      };
      


      // 调用API提交订单（禁用内部loading）
      const orderResult = await apiService.submitOrder(orderData, { showLoading: false });
      
      wx.hideLoading();
      wx.showToast({
        title: '下单成功',
        icon: 'success'
      });

      // 清空餐车
      this.setData({
        myOrderItems: [],
        myOrderCount: 0,
        showCartPopup: false
      });

      // 跳转到订单页面
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/orders/orders'
        });
      }, 1500);
      
    } catch (error) {
      wx.hideLoading();
      
      console.log('订单提交错误:', error);
      
      // 检查是否是业务错误（有code字段）
      if (error.code && typeof error.code === 'number') {
        // 业务错误，显示具体错误信息
        const errorMessage = error.message || '操作失败';
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
        
        // 如果是重复提交订单错误，只提示用户
        if (error.code === 20001) {
          // 重复提交订单的错误信息已经在上面显示了，这里不需要额外处理
        }
        return; // 业务错误不执行后续的本地保存逻辑
      }
      
      // 网络错误或其他错误，保存到本地
      if (error.statusCode === 404 && error.errMsg && error.errMsg.includes('servicewechat.com')) {
        wx.showToast({
          title: '开发环境：已保存到本地',
          icon: 'none',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '下单失败，已保存到本地',
          icon: 'none',
          duration: 2000
        });
      }
      
      // 如果API失败，保存到本地存储作为备份
      const orderData = {
        orderId: 'order_' + Date.now(),
        roomId: this.data.roomInfo.roomId || 'default',
        roomTitle: this.data.roomInfo.title || '',
        items: this.data.myOrderItems.map(item => ({
          dishId: item.id,
          dishName: item.name,
          quantity: item.quantity,
          category: item.category
        })),
        totalCount: this.data.myOrderCount,
        status: 'pending',
        createdAt: new Date().toISOString(),
        creator: '当前用户'
      };

      const orders = wx.getStorageSync('orders') || [];
      orders.unshift(orderData);
      wx.setStorageSync('orders', orders);

      wx.showToast({
        title: '订单已保存到本地',
        icon: 'success'
      });

      // 清空餐车
      this.setData({
        myOrderItems: [],
        myOrderCount: 0,
        showCartPopup: false
      });
    }
  },


});
